﻿var questionID = -2;
var questionType = "singleResponse";
var responseHandler = "addKeypadUser";

function addKeypadUser(deviceID, response) {
    $.ajax({
        type: 'POST',
        url: "/Participant/AddKeypadUser",
        data: { pollID: $('#pollid').val(), deviceID: deviceID },
        success: function(response) {
            if (response == "True") {
                 $('#bulkAddKeypadMessage').remove();
                 document.getElementById('bulkAddKeypadContainer').vAlign = "top";
                 document.getElementById('bulkAddKeypadContainer').innerHTML += deviceID+"<br/>"; 
            }
            else {
                alert("This user is already a participant.");
            }
        }
    });
}
function disableSave() {
    $('#submitEditList').attr("disabled", true);
    $('#submitEditList').val("Saved");
}
function update(event) {
    var items = document.getElementsByTagName("td");
    var lingen = document.getElementsByTagName("th").length;
    var tryer = false;
    var a=0;
    var b=0;
    for (var i = 0; i < items.length; i++) {
        if (items[i].hasChildNodes()){
           var check = items[i].childNodes[0].nodeName;
           if (items[i].childNodes[0].name != items[i].childNodes[0].value && items[i].childNodes[0].nodeName == "INPUT") {
               tryer = true;
               a++;
               $.ajax({
                   type: 'POST',
                   url: "EditingList",
                   data: { pollID: $('#pollid').val(), participantID: items[i].parentElement.id, fieldID: document.getElementsByTagName("th")[i % lingen].id, value: items[i].childNodes[0].value },
                   success: b++,
               });
           }
           else if (items[i].childNodes[0].name != items[i].childNodes[0].value && items[i].childNodes[0].nodeName == "SELECT") {
               tryer = true;
               a++;
               $.ajax({
                   type: 'POST',
                   url: "EditingEntity",
                   data: { pollID: $('#pollid').val(), participantID: items[i].parentElement.id, value: items[i].childNodes[0].value },
                   success: b++,
               });
           }
        }
   }
   if(a==b) {
        disableSave();
   }
}
function addField() {
    if ($('#addfield').val() != "") {
        $.ajax({
               type: 'POST',
               url: "AddField",
               data: { pollID: $('#PollID').val(), name: $('#addfield').val() },
               success: function() {
                    window.location.href = "EditList?pollID=" + $('#PollID').val() + "&pollName=" + $('#PollName').val();
               }
        });
    }
}
function addGroup() {
    if ($('#addgroup').val() != "") {
        $.ajax({
               type: 'POST',
               url: "AddGroup",
               data: { pollID: $('#pollid').val(), name: $('#addgroup').val() },
               success: function() {
                    window.location.href = "EditList?pollID=" + $('#pollid').val() + "&pollName=" + $('#pollname').val();
               }
        });
    }
}
function deleting(element) {
    if ($('#com'+element).val()=="True") {
        alert("There are demographic comparative question(s) associated with this field, therefore this field can't be deleted.");
        return;
    }
    if ($('#dem'+element).val()=="True") {
        var c = confirm("There are demographic question(s) with this field. Do you want to convert them to custom questions?");
        if (c==false) {return;}
    }
    $.ajax({
        type: 'POST',
        url:"DeleteField",
        data: { pollID: $('#PollID').val(), fieldID: element },
        success: function() {
            window.location.href = "EditList?pollID=" + $('#PollID').val() + "&pollName=" + $('#PollName').val();
        }
    });
}
function keypadListenerError() {}
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};
function addBulk() {
    if ($('#message').text() =="User already added") {alert("This user is already a participant.");}
    else if ($('#message').text()=="Unsuccessful") {alert("Something when wrong");}
    else if ($('#message').text() == "Success") {
        $('#bulkAddKeypadMessage').remove();
        $('#bulkAddKeypadContainer').append("<div>" + $('#bulk').val() + "</div>");
    }
}
function addEmail(){
    if ($('#message').text()=="No such user") 
    { 
        if (!isValidEmailAddress($('#email').val()))
        {
            alert("This email address is not valid");
        }
        else
        {
            var r = confirm("There is no such poll user with this email address. Would you like to create one?");
            if (r==true)
            {
                var a = $('#email').val();
                window.location.href = "../Account/AccountManager?role=Poll%20User&email=" + a + "&pollID=" + $('#pollid').val() + "&pollName=" + $('#pollname').val();
                $('#Email').val() = a;
            }
        }
    }
    else if ($('#message').text() =="User already added") {alert("This user is already a participant.");}
    else if ($('#message').text()=="Unsuccessful") {alert("Something when wrong");}
    else if ($('#message').text() == "Success") {
        $('#bulkAddKeypadMessage').remove();
        $('#bulkAddKeypadContainer').append("<div>" + $('#email').val() + "</div>");
        $('#email').val("");
    }
}
function deleted() {
     window.location.reload();
}
function validate() {
    var items = document.getElementsByClassName('group');
    var final = true;
    for (var i=0; i<items.length; i++) {
        var thing = document.getElementById(items[i].name);
        document.getElementById("a"+items[i].name).innerHTML="";
        if (items[i].value=="True" && thing.checked==true) { 
            document.getElementById("a"+items[i].name).innerHTML="<font color=\"red\">Sure</font>";
            final=false;            
        }
    }
    if (final==false) {
        var r = confirm("Some participants are already in other groups, those marked with \"Sure\". Click ok if you want to change their group if not cancel and choose again.");
        if (r==false) { return false; }
    }
}
$(document).ready(function() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
        vars[key] = value;
    });
    $('#email').val(vars["email"]);
    var lastTemplateID = $("#selectedTemplateID").val() != "" ? $("#selectedTemplateID").val() : -1;
    $('#selectedTemplateID').live("change", function() {
        if ($('#hasCompare').val()=="True") {
            alert("There are demographic comparative questions, therefore templates can't be changed");
            $("#selectedTemplateID").val(lastTemplateID);
            return;
        }
        if ($('#hasdems').val()=="True") {
        var c = confirm("There are demographic question(s) with existing field(s). Do you want to convert them to custom questions?");
        if (c==false) { $("#selectedTemplateID").val(lastTemplateID); return;}
    }
        var selectedTemplateID = $("#selectedTemplateID").val() != "" ? $("#selectedTemplateID").val() : -1;
        $.ajax({
            url: "/Poll/ApplyParticipantListTemplate",
            data: ({ pollID: $("#poll_pollID").val(), templateID: selectedTemplateID, lastTemplateID: lastTemplateID }),
            cache: false,
            success: function(html) {
                $('.questions').html(html);
                $('#hasdems').val("False");
            }
        });
        lastTemplateID = $("#selectedTemplateID").val() != "" ? $("#selectedTemplateID").val() : -1;
        return false;
    });
    $('input').each(function() {
        $(this).click(function() {
            if ($('#submitEditList').attr("disabled")) {
                $('#submitEditList').val("Save");
                $('#submitEditList').attr("disabled", false);
            }
        });
    });
    $('#submitKeypadUser').click(function() {
        if ($('#deviceID').val() == "") {
            alert("Please enter a Device ID");
            return false;
        }
        $.ajax({
            type: 'POST',
            url: "/Participant/AddKeypadUser",
                    data: { pollID: $('#pollid').val(), deviceID: $('#deviceID').val() },
            success: function(response) {
                if (response == "True") {
                     $('#bulkAddKeypadMessage').remove();
                     $('#bulkAddKeypadContainer').append("<div>" + $('#deviceID').val() + "</div>");
                     $('#deviceID').val("");   
                }
                else {
                    alert("This user is already a participant.");
                }
            }
        });
    });
});